package qrcode

import (
	"context"
	"git.mycaigou.com/gfyx/micro-gfyx-user-service/infrastructure/common/utils"
	"git.myscrm.cn/golang/stark/v4"
	"gorm.io/gorm"
)

type qrcodeRepository struct {
}

func NewQrcodeRepository() QrcodeRepositoryIface {
	return &qrcodeRepository{}
}

func (r *qrcodeRepository) Create(ctx context.Context, po *QrcodePo) (*QrcodePo, error) {
	db := stark.MySQLConn.Get(ctx)
	err := db.Table(po.TableName()).Create(po).Error
	return po, err
}

func (r *qrcodeRepository) QueryList(ctx context.Context, condition map[string]interface{}, pageInfo *utils.PageInfo, orderBy string) (int64, []*QrcodePo, error) {
	var result []*QrcodePo
	var count int64

	db := stark.MySQLConn.Get(ctx)
	db = db.Table(QrcodePo{}.TableName()).Where(condition)

	err := db.Count(&count).Error
	if err != nil {
		return 0, nil, err
	}

	if pageInfo != nil && pageInfo.PageSize > 0 && pageInfo.Page > 0 {
		db = db.Offset((pageInfo.Page - 1) * pageInfo.PageSize).Limit(pageInfo.PageSize)
	}

	if orderBy != "" {
		db = db.Order(orderBy)
	}

	err = db.Find(&result).Error
	if err != nil {
		if err == gorm.ErrRecordNotFound {
			return 0, result, nil
		}
		return 0, nil, err
	}
	return count, result, nil
}

func (r *qrcodeRepository) QueryOne(ctx context.Context, condition map[string]interface{}) (*QrcodePo, error) {
	result := &QrcodePo{}
	db := stark.MySQLConn.Get(ctx)
	err := db.Table(QrcodePo{}.TableName()).Where("oss_file_path <> ''").Where(condition).First(result).Error
	if err != nil {
		if err == gorm.ErrRecordNotFound {
			return nil, nil
		}
		return nil, err
	}
	return result, nil
}

func (r *qrcodeRepository) UpdateById(ctx context.Context, id int64, updates map[string]interface{}) error {
	db := stark.MySQLConn.Get(ctx)
	err := db.Table(QrcodePo{}.TableName()).Where("id =?", id).Updates(updates).Error
	if err != nil {
		return err
	}
	return nil
}
